require 'fileutils'
class SiteController < ApplicationController
  include ActionView::Helpers::NumberHelper
  before_filter :require_admin, :only => [:restart,:log_admin]
  layout 'application', :except => [:restart,:log_admin]
  
  def index
    @title = '首页'
    @posts = Post.all(:page => params[:page])
  end

  # => 关于
  def about
    @title = '关于我'
  end

	def plan
		@title = '开发计划'
	end

  # => 搜索
  def search
    @title = '日志搜索'
    @q = params[:q]
    @posts = Post.title_or_content_like(@q)
    flash[:notice] = '没有找到匹配的日志！' if @posts.empty?
  end

  # => 日志归档
  def archive
    @title = "#{params[:id]}日志归档"
    if params[:id]
      @posts = Post.all(:conditions => ["DATE_FORMAT(created_at,\"%Y-%m\") = ?",params[:id]])
    else
      @posts = Post.all
    end
  end

  # => tags页面文章搜索
  def tags
    @title = "#{params[:tag]}相关的日志"
    @posts = Post.tags_like(params[:tag])
    flash[:notice] = '没有找到相关的日志！' if @posts.empty?
  end

  # => 重启站点
  def restart
    @restart_file = File.join(RAILS_ROOT,'tmp','restart.txt')
    #File.chmod(0777,restart_file) unless File.writable?(restart_file)
    if request.post?
      if FileUtils.touch @restart_file
        text = "<span style=\"color:green\">重启成功！</span>"
      else
        text = "<span style=\"color:red\">重启失败！</span>"
      end
      render :text => text
    end
  end

  # => 日志管理
  def log_admin
    log_dir = File.join(RAILS_ROOT,'log')
    @log_file_arr = []
    Dir.new(log_dir).each do |file_name|
      log_file_path = File.join(log_dir,file_name)
      @log_file_arr << [file_name,log_file_path,File.stat(log_file_path).size] if File.extname(file_name) == '.log'
    end
    if params[:log_path] # => 查看日志
      render_info = ''
      if File.exist?(params[:log_path])
        File.open(params[:log_path]).each_line do |line|
          render_info << line
        end
      end
    elsif params[:file_path] # => 下载日志
      if File.exist?(params[:file_path])
        send_file params[:file_path]
      end
    elsif params[:clear_path] # => 清空日志
      if File.exist?(params[:clear_path])
        f = File.open(params[:clear_path],'w')
        f.close
        render_info = number_to_human_size(File.stat(params[:clear_path]).size)
      end
    end
    if render_info
      render :text => render_info
    end
  end
end
